package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGoupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGoupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGoupDao checkGoupDao;

    @Override
    /*新增检查组，同时往中间表添加数据*/
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGoupDao.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        if (checkitemIds != null && checkitemIds.length > 0) {
            /*循环往中间表添加*/
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("checkgroupId", checkGroupId);
                map.put("checkitemId", checkitemId);
                checkGoupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        /*mybatis提供的分页插件*/
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckItem> page = checkGoupDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<CheckItem> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGoupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkGoupDao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    public void edit(CheckGroup checkGroupId, Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            Map map = new HashMap();
            map.put("checkGroupId", checkGroupId);
            map.put("checkitemIds", checkitemIds);
            checkGoupDao.edit(map);
        }
    }

    @Override
    public Result delete(Integer id) {
        try {
            checkGoupDao.delete(id);
            return new Result();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("当前检查相已被引用,不能删除");
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGoupDao.findAll();
    }
}
